/**
 * https://juejin.cn/post/6844903933320790024
 * https://zh.javascript.info/cookie
 *
 */

// 获取指定名称的cookie
export function getCookie(name) {
  let strcookie = document.cookie; //获取cookie字符串
  let arrcookie = strcookie.split('; '); //分割
  //遍历匹配
  for (let i = 0; i < arrcookie.length; i++) {
    let arr = arrcookie[i].split('=');
    if (arr[0] == name) {
      return arr[1];
    }
  }
  return '';
}

/**
 * 设置日期
 * @param expiredays 过期天数 cookie 最长400天
 * @returns
 */
export const expireTime = expiredays => {
  const exdate = new Date();
  exdate.setDate(exdate.getDate() + expiredays);
  return exdate;
};

/**
 * 写入保存 cookie
 * @param key 键
 * @param value 值
 * @param expiredays 过期天数
 */
export const setCookies = (key, value, expiredays = 365 * 1) => {
  const cookieStr = encodeURIComponent(key) + '=' + encodeURIComponent(value) + (expiredays ? ';expires=' + expireTime(expiredays).toUTCString() : '');
  document.cookie = cookieStr + ';path=/';
};

/**
 * 取回cookie
 * @param key 键
 * @returns
 */
export function getCookies(key) {
  if (document.cookie.length > 0) {
    let c_start = document.cookie.indexOf(key + '=');
    if (c_start !== -1) {
      c_start = c_start + key.length + 1;
      let c_end = document.cookie.indexOf(';', c_start);
      if (c_end === -1) c_end = document.cookie.length;
      return decodeURIComponent(document.cookie.substring(c_start, c_end));
    }
  }
  return '';
}
